import Taro, { getCurrentInstance, eventCenter } from "@tarojs/taro";
import BaseComponents from "@/components/BaseComponents";
import { View, Image } from "@tarojs/components";
import IconFont, { iconType } from "@/components/IconFont";
import React, { FC } from "react";
import styles from "./index.module.scss";
import { updateUserinfoApi, getUserinfoApi } from '@/api';
import { isLogin } from '@/utils/common'
import blankPng from '@/images/tabBar/Icon_blank.png'
// import tabbarCenterShadow from '@/images/tabBar/tabbar_center_shadow.png'


export const TAB_BAR_HEIGHT = 70;

type listType = {
  type: string;
  pagePath?: string;
  iconPath: string;
  selectedIconPath: string;
  text?: string;
  icon?: iconType;
};

interface Props { }
interface State {
  selected: number;
  color: string;
  selectedColor: string;
  list: listType[];
}

/**
 *
 * @description 这个地方请不要使用 `iconfont`
 *  1. 因为使用 `CoverView` 渲染在真机有问题  （已经不使用 `CoverView` 了）
 *  2. 为了保持和 `app.config.ts` `tabbar` 一致
 */
class TabBar extends BaseComponents<Props, State> {
  $instance = getCurrentInstance();

  constructor(props: Props) {
    super(props);

    this.state = {
      selected: 0,
      color: "#999",
      selectedColor: "#000",
      list: [
        {
          type: "normal",
          iconPath: require("@/images/tabBar/Icon_grain.png"),
          selectedIconPath: require("@/images/tabBar/ic_grain_on.png"),
          pagePath: "/pages/index/index",
          text: "首页",
        },
        {
          type: "center",
          iconPath: "",
          selectedIconPath: ""
        },
        {
          type: "normal",
          iconPath: require("@/images/tabBar/Icon_my.png"),
          selectedIconPath: require("@/images/tabBar/ic_my_on.png"),
          pagePath: "/pages/my/index",
          text: "我的",
        },
      ],
    };
  }

  componentWillMount() {
    const onShowEventId = this.$instance.router?.onShow || "";
    eventCenter.on(onShowEventId, this.onShow);
  }

  componentWillUnmount() {
    const onShowEventId = this.$instance.router?.onShow || "";
    eventCenter.off(onShowEventId, this.onShow);
  }

  onShow = () => {
    const path = this.$instance.router?.path || "";
    if (path !== "") {
      const { list } = this.state;

      const res = list.findIndex((v) => {
        return path === v.pagePath;
      });

      if (res !== -1) {
        this.setState({
          selected: res,
        });
      }
    }
  };

  switchTab = (item, index) => {
    const { selected } = this.state;
    if (index === selected) return;
    const url = item.pagePath;
    Taro.switchTab({ url });
    this.setState({
      selected: index,
    });
  };

  getLocation = () => {
    if (isLogin()) {
      if (!Taro.getStorageSync('userInfo').longitude) {
        Taro.getLocation({
          type: 'wgs84',
          success: function (res) {
            if (Taro.getStorageSync('userInfo'))
              updateUserinfoApi({ code: Taro.getStorageSync('userInfo').code, longitude: res.longitude, latitude: res.latitude }).then((res) => {
                if (res) {
                  getUserinfoApi().then((res) => {
                    if (res) {
                      Taro.setStorageSync('userInfo', res);
                    }
                  })
                }
              })
          }
        })
      }
    }
  }


  render() {
    const { list, selected, selectedColor, color } = this.state;
    return (
      <View
        style={{
          height: TAB_BAR_HEIGHT,
        }}
      >
        {/* <Image src={tabbarCenterShadow} className={styles.tabbarCenterShadow}></Image> */}
        <View className={styles.tabBar}>
          {/* <View className={styles.tabBarBorder}></View> */}

          {list.map((item, index) => {
            const style: React.CSSProperties = {
              color: selected === index ? selectedColor : color,
            };

            return item.type == "center" ? (
              <View
                className={styles.tabBarItem}
                onClick={() => { this.getLocation() }}
                key={index}
              >
                <CenterBar></CenterBar>
              </View>
            ) : (
              <View
                className={styles.tabBarItem}
                onClick={this.switchTab.bind(this, item, index)}
                key={item.pagePath}
              >
                <Image
                  src={
                    selected === index ? item.selectedIconPath : item.iconPath
                  }
                ></Image>

                {/* <IconFont style={style} icon={item.icon}></IconFont> */}

                <View className={styles.icon} style={style}>
                  {item.text}
                </View>
              </View>
            );
          })}
        </View>
      </View>
    );
  }
}

const CenterBar = React.memo(() => {
  return (
    <View className={styles.centerTabBar}>
      <View className={styles.centerTabBar_circleBox}>
        <Image src={blankPng} className={styles.centerTabBar_Image}></Image>
      </View>
    </View>
  );
}
);

export default TabBar;
